#!/usr/bin/python
# -*- coding: utf-8 -*-

from dbutil import dbutil
from user import user


class userdao:

    def __init__(self):
        self.db = dbutil()


    def findall(self,name,idCard):
        db = self.db.getDb()
        cursor = db.cursor()
        # 使用 execute()  方法执行 SQL 查询
        querysql = "SELECT create_time,where_from,id_card,person_name,sex,temp,what,health,age from user where 1=1 "

        if name != '':
            querysql += " and person_name like '%" + name +"%'"
        if idCard != '':
            querysql += " and id_card like '%" + idCard +"%'"
        try:
            # 执行SQL语句
            cursor.execute(querysql)
            # 获取所有记录列表
            results = cursor.fetchall()
            users = []
            for row in results:
                createtime = row[0]
                wherefrom = row[1]
                idcard = row[2]
                personname = row[3]
                sex = row[4]
                temp = row[5]
                what = row[6]
                health = row[7]
                age = row[8]
                users.append(user(createtime,wherefrom,idcard,personname,sex,temp,health,what , age))
            return users
        except:
            print "Error: unable to findall user"

    def insert(self,user):

        db = self.db.getDb()
        cursor = db.cursor()
        health = ""
        #判断是否健康
        if float(user.temp) < 37.6:
            health = "健康"
        else:
            health = "不健康"
        # 使用 execute()  方法执行 SQL 查询
        insertsql = "insert into user (create_time,where_from,id_card,person_name,sex,temp,what,health,age) values ('%s', '%s', '%s', '%s', '%s' ,'%s' ,'%s' , '%s' ,'%s' )" % \
                   (user.time,user.where,user.idCard,user.name,user.sex,user.temp,user.what , health,user.age)

        try:
            # 执行sql语句
            cursor.execute(insertsql)
            # 提交到数据库执行
            db.commit()
            return True
        except Exception as e:
            print('插入异常' ,e )
            # 发生错误时回滚
            db.rollback()
            return False;

    def delete(self,idCard):
        db = self.db.getDb()
        cursor = db.cursor()
        # 使用 execute()  方法执行 SQL 查询
        deleteSql = "delete from user where id_card=%s" % idCard

        try:
            # 执行sql语句
            cursor.execute(deleteSql)
            # 提交到数据库执行
            db.commit()
            return True
        except:
            # 发生错误时回滚
            db.rollback()
            return False